import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/constant/app_config.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/err/fb_error.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/network/http_manger.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/network/intercept/add_header_Intercept.dart';
import 'package:library_base/page/2_404_error.dart';
import 'package:library_base/utils/device_util.dart';
import 'package:library_base/utils/spUtil/sp_util.dart';
import 'package:library_base/utils/sp_util.dart';
import 'package:logger/logger.dart';
import 'package:library_base/base/base_state_config.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_bugly/flutter_bugly.dart';


class GlobalConfigService extends GetxService {
  ///程序初始化操作
  Future<GlobalConfigService> initApp() async {
    initSystemConfig();
    await initSPUtil();
    initGlobalErrorPage();
    await initFBHttp();
    initLog();
    // await initFlutterBugly();
    // initWxSdk();
    // await ScreenUtil.ensureScreenSize();
    return this;
  }

  ///初始化腾讯
  initFlutterBugly() async{
    FlutterBugly.init(
        androidAppId: Constant.androidAppId,
        iOSAppId: Constant.iOSAppId,
        enableHotfix: true,
        channel: DeviceUtil.getPlatform().name,
        customUpgrade: false
    );
  }

  ///初始化系统常用配置
  initSystemConfig(){
    // WidgetFlutterBinding用于与 Flutter 引擎进行交互。Firebase.initializeApp()需要调用本机代码来初始化 Firebase，并且由于插件需要使用平台通道来调用本机代码，这是异步完成的，因此您必须调用ensureInitialized()以确保您拥有WidgetsBinding.
    WidgetsFlutterBinding.ensureInitialized();
    //屏幕刷新率和显示率不一致时的优化，必须运行在WidgetsFlutterBinding.ensureInitialized()之后
    GestureBinding.instance!.resamplingEnabled = true;
    //Android环境状态栏透明,导航栏白色
    if (DeviceUtil.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  }

  ///Log初始化
  initLog() {
    Logger.level = AppConfig.isTestEnvironment ? Level.verbose : Level.error;
  }

  ///初始化友盟
  ///1.pubspec.yaml依赖umeng_common_sdk: ^1.2.4;
  ///2.导入import 'package:umeng_common_sdk/umeng_common_sdk.dart';
// initUmengCommonSdk() async{
//   String channel = await ChannelUtil.getChannel();
//   UmengCommonSdk.initCommon('607552ba5844f15425d14f03', '6075530a5844f15425d151b2', channel);
//   UmengCommonSdk.setPageCollectionModeManual();
// }

  ///初始化微信
  ///1.pubspec.yaml依赖fluwx;
  ///2.导入 import 'package:fluwx/fluwx.dart';
  initWxSdk() async {
    if (DeviceUtil.isMobile && false) {
      // await registerWxApi(appId: "wxfdba5c8a01643f82", doOnAndroid: true, doOnIOS: true, universalLink: "https://www.idengta.com/app/lighthouse/");
    }
  }

  ///初始化本地存储
  initSPUtil() async {
    await SPUtil.init();
  }

  initScreenUtil() async{
    await ScreenUtil.ensureScreenSize();
  }

  initFBHttp() async {
    requestErr(FBError error) {
      logger.e("网络全局监听错误---${error.toString()}");
    }
    FBSpUtils().init();
    FBHttpUtil.globalErrCallBack = requestErr;
    HttpConfig.baseUrl = AppConfig.env.apiUrl;
    HttpManger().addIntercept(AddHeaderIntercept());
    HttpManger().addIntercept(LogInterceptor(requestBody: true, responseBody: true));
    HttpManger().setBadCertificateCallback((cert, host, port) => true);
  }

  ///发布版本使用全局的错误页面,否则为系统的错误页面,这样开发方便调试
  void initGlobalErrorPage() {
    if (Constant.isReleaseMode) {
      ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
        return Error404Screen();
      };
    }
  }

  @override
  void onReady() {
    ScreenUtil.init(Get.context!, designSize: const Size(750, 1624)).then((value){
      BaseUiConfig.globalStatusBarColor = ThemeUtil.getTheme().secondaryBgColor();

      BaseUiConfig.globalPageBackgroundColor = ThemeUtil.getTheme().colorScheme.secondary;

      ///状态栏是否可见
      if(GetPlatform.isAndroid || GetPlatform.isIOS ){
        BaseUiConfig.globalIsStatusBarVisible = true;
      }else{
        BaseUiConfig.globalIsStatusBarVisible = false;
      }

      BaseUiConfig.globalNavigationBarHeight = 120.w;

      ///标题栏背景颜色
      BaseUiConfig.globalNavigationBarBackgroundColor = ThemeUtil.getTheme().secondaryBgColor();

      ///标题栏文字颜色
      BaseUiConfig.globalNavigationBarContentColor = ThemeUtil.getTheme().normalTextColor();
      BaseUiConfig.globalTitleSize = 36.sp;
      BaseUiConfig.globalBackIcon = Icons.arrow_back_ios_rounded;

      EasyRefresh.defaultHeaderBuilder = () => ClassicHeader(
        backgroundColor: Colors.transparent,
        textStyle: TextStyle(fontSize: 30.sp, color: ThemeUtil.getTheme().colorScheme.primary),
        messageStyle: TextStyle(fontSize: 25.sp, color: ThemeUtil.getTheme().colorScheme.primary),
        iconTheme: IconThemeData(color: ThemeUtil.getTheme().colorScheme.primary),
        clamping: BaseUiConfig.globalClamping,
        triggerWhenReach: BaseUiConfig.globalImmediately,
        infiniteOffset: BaseUiConfig.globalInfinite ? 70 : null,
        dragText: MultiLanguage.pullDownToRefresh.tr,
        armedText: MultiLanguage.releaseRefresh.tr,
        readyText: MultiLanguage.refreshing.tr,
        processingText: MultiLanguage.refreshing.tr,
        processedText: MultiLanguage.loadedSuccessfully.tr,
        noMoreText: 'No more'.tr,
        mainAxisAlignment: MainAxisAlignment.center,
        failedText: MultiLanguage.loadingFail.tr,
        messageText: MultiLanguage.lastUpdated.tr,
      );
      EasyRefresh.defaultFooterBuilder = () => ClassicFooter(
        dragText: 'Pull to load'.tr,
        armedText: 'Release ready'.tr,
        readyText: 'Loading...'.tr,
        processingText: 'Loading...'.tr,
        processedText: 'Succeeded'.tr,
        noMoreText: 'No more'.tr,
        failedText: 'Failed'.tr,
        messageText: 'Last updated at %T'.tr,
      );
    });
  }

}
